//
//  AccelerometerManager.m
//  Seizure
//
//  Created by student on 2/14/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "AccelerometerManager.h"
#import "AccelerometerFilter.h"

#define accelerometerFreq 100          //100 Hz

@implementation AccelerometerManager

- (id)init
{
    self = [super init];
    if (self) {
        // setup filter 
        [self changeFilter:[HighpassFilter class]];
        
        state = NOT_RUNNING;
        
        float version = [[[UIDevice currentDevice] systemVersion] floatValue];
        // setup motion detection tracker
        if (version >= 5.0)
        {
            newDevice = YES;
            // version 5 and greater will use accelManager
            accelManager = [[AccelerometerManager alloc] init];
            
        }
        else
        {
            newDevice = NO;
            // lower versions will use the UIAccelDelegate
            [[UIAccelerometer sharedAccelerometer] setUpdateInterval:1.0 / kUpdateFrequency];
            [[UIAccelerometer sharedAccelerometer] setDelegate:self];
        }
        
        isDetectingAcceleration = NO;
        
        seizureLog = [[EventLog alloc] init:nil end:nil location:nil];
        
        
        // AUDIO STUFF
        NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
                                             pathForResource:@"alertSound"
                                             ofType:@"mp3"]];
        
        NSError *error;
        audioPlayer = [[AVAudioPlayer alloc]
                       initWithContentsOfURL:url
                       error:&error];
        if (error)
        {
            NSLog(@"Error in audioPlayer: %@", 
                  [error localizedDescription]);
        } else {
            //            audioPlayer.delegate = self;
            [audioPlayer prepareToPlay];
        }
        /////////
        self.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"Motion Detection" image:nil tag:0];
    }
    return self;
}

- (void)startGettingData:(id)sender
{
    self.isDetectingAcceleration = YES;
    
    if (newDevice){
        if (motionQueue == nil)
            motionQueue = [[NSOperationQueue alloc] init];
        if (motionManager == nil)
            motionManager = [[CMMotionManager alloc] init];
        
        [motionManager startAccelerometerUpdatesToQueue:[[NSOperationQueue alloc] init] withHandler:
         ^(CMAccelerometerData *accelerometerData, NSError *error){
             
             dispatch_async(dispatch_get_main_queue(), ^{
                 
                 NSLog(@"X: %f", accelerometerData.acceleration.x);
                 NSLog(@"Y: %f", accelerometerData.acceleration.y);
                 NSLog(@"Z: %f", accelerometerData.acceleration.z);
                 [filter addAccelerationX:accelerometerData.acceleration.x
                                        y:accelerometerData.acceleration.y 
                                        z:accelerometerData.acceleration.z];
                 [self detectSeizure];
                 [self updateGraph];
             });
         }];
    }
    else
    {
        // older device is already setup
        [[UIAccelerometer sharedAccelerometer] setDelegate:self];
    }
    state = RUNNING;
    
}

- (void)changeFilter:(Class)filterClass
{
	// Ensure that the new filter class is different from the current one...
	if(filterClass != [filter class])
	{
		// And if it is, release the old one and create a new one.
		filter = nil;
		filter = [[filterClass alloc] initWithSampleRate:kUpdateFrequency cutoffFrequency:5.0];
		// Set the adaptive flag
		filter.adaptive = YES;
	}
}

@end
